<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { messageApi, type Message } from '../../services/api'

// 导航相关
const router = useRouter()
const character = ref<any>(null)

// 聊天状态
const messages = ref<Message[]>([])
const newMessage = ref('')
const isLoading = ref(false)
const error = ref<string | null>(null)

// 滚动到最新消息
const messagesEndRef = ref<HTMLElement | null>(null)

const scrollToBottom = () => {
  nextTick(() => {
    messagesEndRef.value?.scrollIntoView({ behavior: 'smooth' }) 
  })
}

// 获取消息历史
const fetchMessages = async () => {
  try {
    isLoading.value = true
    error.value = null
    // 这里应该使用实际的角色ID，现在使用一个默认值
    const characterId = 1
    messages.value = await messageApi.getByCharacterId(characterId)
  } catch (err) {
    error.value = '获取消息失败: ' + (err as Error).message
    console.error('获取消息失败:', err)
  } finally {
    isLoading.value = false
    scrollToBottom()
  }
}

// 发送消息
const sendMessage = async () => {
  if (!newMessage.value.trim() || isLoading.value) {
    return
  }
  
  try {
    // 添加用户消息到界面
    const userMessage: Message = {
      content: newMessage.value,
      sender: 'user',
      timestamp: new Date().toISOString()
    }
    
    messages.value.push(userMessage)
    const messageToSend = newMessage.value
    newMessage.value = ''
    scrollToBottom()
    
    // 模拟发送消息到后端
    isLoading.value = true
    await messageApi.create({
      content: messageToSend,
      sender: 'user'
    })
    
    // 模拟接收角色回复（实际应该通过WebSocket或轮询实现）
    setTimeout(async () => {
      const replies = [
        '这听起来很有趣！',
        '我明白了，谢谢你分享！',
        '哇，你的想法真棒！',
        '我们可以一起做更多有趣的事情！',
        '你真是个有趣的人！'
      ]
      
      const characterMessage: Message = {
        content: replies[Math.floor(Math.random() * replies.length)],
        sender: 'character',
        timestamp: new Date().toISOString()
      }
      
      messages.value.push(characterMessage)
      isLoading.value = false
      scrollToBottom()
      
      // 保存角色回复到后端
      try {
        await messageApi.create({
          content: characterMessage.content,
          sender: 'character'
        })
      } catch (err) {
        console.error('保存角色消息失败:', err)
      }
    }, 1000)
  } catch (err) {
    error.value = '发送消息失败: ' + (err as Error).message
    console.error('发送消息失败:', err)
    isLoading.value = false
  }
}

// 组件挂载时获取消息
onMounted(() => {
  fetchMessages()
})

// 组件卸载前清理
onBeforeUnmount(() => {
  // 可以在这里清理定时器或其他资源
})
</script>

<template>
  <div class="chat-container neo-brutalist">
    <!-- 导航栏 -->
    <div class="navbar neo-brutalist">
      <button 
        class="back-btn neo-brutalist btn btn--secondary"
        @click="router.push('/home')"
      >
        ← 返回
      </button>
      <h1>{{ character?.name || '聊天界面' }}</h1>
    </div>
    
    <!-- 内容区域 -->
    <div class="chat-content">
    
    <!-- 错误信息 -->
    <div v-if="error" class="error-message neo-brutalist">
      {{ error }}
    </div>

    <!-- 消息区域 -->
    <div class="messages-container">
      <div 
        v-for="message in messages" 
        :key="message.id"
        :class="['message', message.sender]"
      >
        <div class="message-content neo-brutalist">
          <div class="message-text">{{ message.content }}</div>
          <div class="message-time">
            {{ new Date(message.timestamp || '').toLocaleTimeString() }}
          </div>
        </div>
      </div>
      
      <!-- 加载指示器 -->
      <div v-if="isLoading" class="message character">
        <div class="message-content neo-brutalist">
          <div class="typing-indicator">
            <span></span>
            <span></span>
            <span></span>
          </div>
        </div>
      </div>
      
      <div ref="messagesEndRef"></div>
    </div>
    
    <!-- 输入区域 -->
    <div class="input-container neo-brutalist">
      <form @submit.prevent="sendMessage">
        <input 
          v-model="newMessage"
          type="text" 
          placeholder="输入消息..."
          :disabled="isLoading"
          class="neo-brutalist-input"
        />
        <button 
          type="submit"
          :disabled="!newMessage.trim() || isLoading"
          class="send-button neo-brutalist btn btn--primary"
          :class="{ 'btn--disabled': !newMessage.trim() || isLoading }"
        >
          发送
        </button>
      </form>
    </div>
    </div>
  </div>
</template>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 1200px;
  margin: 0 auto;
  background: #fff;
  overflow: hidden;
}

.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 1rem 1.5rem;
  background: var(--neo-brutalist-yellow);
  border-bottom: 4px solid #000;
  box-shadow: 8px 8px 0 #000;
  position: relative;
  z-index: 100;
}

.navbar h1 {
  margin: 0;
  font-size: 1.5rem;
  font-family: 'Bebas Neue', sans-serif;
  letter-spacing: 2px;
  text-align: center;
  flex-grow: 1;
}

.back-btn {
  background: none;
  border: none;
  font-size: 1.2rem;
  cursor: pointer;
  padding: 0.5rem;
  margin-right: 1rem;
}

.chat-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  padding: 1rem;
  gap: 1rem;
  overflow: hidden;
}

.chat-header {
  background: var(--neo-brutalist-yellow);
  color: #000;
  padding: 1rem;
  border: none;
}

.character-info {
  display: flex;
  align-items: center;
  gap: 1rem;
}

.character-info .emoji {
  font-size: 2rem;
}

.character-info h2 {
  margin: 0;
  font-size: 1.5rem;
  font-family: 'Bebas Neue', sans-serif;
  letter-spacing: 2px;
}

.error-message {
  padding: 1rem;
  background-color: var(--neo-brutalist-red);
  color: #fff;
  text-align: center;
  margin: 1rem;
}

.messages-container {
  flex: 1;
  padding: 1rem;
  overflow-y: auto;
  display: flex;
  flex-direction: column;
  gap: 1rem;
}

.message {
  display: flex;
  max-width: 80%;
}

.message.user {
  align-self: flex-end;
}

.message.character {
  align-self: flex-start;
}

.message-content {
  padding: 0.75rem 1rem;
  position: relative;
  background: #fff;
  border: 4px solid #000;
}

.message.user .message-content {
  background: var(--neo-brutalist-yellow);
  color: #000;
}

.message.character .message-content {
  background: #e0e0e0;
  color: #000;
}

.message-text {
  margin-bottom: 0.25rem;
  word-wrap: break-word;
}

.message-time {
  font-size: 0.75rem;
  opacity: 0.8;
  text-align: right;
}

.typing-indicator {
  display: flex;
  align-items: center;
  gap: 0.25rem;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background: #000;
  border-radius: 50%;
  display: inline-block;
  animation: typing 1.4s infinite ease-in-out;
}

.typing-indicator span:nth-child(1) {
  animation-delay: -0.32s;
}

.typing-indicator span:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}

.input-container {
  background: #fff;
  padding: 1rem;
  border: none;
}

.input-container form {
  display: flex;
  gap: 0.5rem;
}

.neo-brutalist-input {
  flex: 1;
  padding: 0.75rem;
  font-size: 1rem;
  border: 4px solid #000;
  box-shadow: 4px 4px 0 #000;
  font-family: 'Roboto Mono', monospace;
}

.neo-brutalist-input:focus {
  outline: none;
  box-shadow: 2px 2px 0 #000;
  transform: translate(2px, 2px);
}

.neo-brutalist-input:disabled {
  background-color: #f5f5f5;
  cursor: not-allowed;
}

/* Neo Brutalist Styles */
.neo-brutalist {
  border: 4px solid #000;
  box-shadow: 8px 8px 0 #000;
  transition: all 0.2s ease;
  border-radius: 4px;
  background-color: #fff;
}

.neo-brutalist:hover {
  box-shadow: 6px 6px 0 #000;
  transform: translate(2px, 2px);
}

.neo-brutalist.btn {
  font-weight: bold;
  padding: 0.75rem 1.5rem;
  text-transform: uppercase;
  letter-spacing: 1px;
  cursor: pointer;
  transition: none;
  font-family: 'Bebas Neue', sans-serif;
  font-size: 1.1rem;
  border: 4px solid #000;
  box-shadow: 4px 4px 0 #000;
}

.neo-brutalist.btn:hover {
  background-color: var(--neo-brutalist-yellow);
  color: #000;
  box-shadow: 2px 2px 0 #000;
  transform: translate(2px, 2px);
}

.neo-brutalist.btn--primary {
  background-color: var(--neo-brutalist-yellow);
  color: #000;
}

.neo-brutalist.btn.btn--disabled {
  background-color: #ccc;
  cursor: not-allowed;
  box-shadow: 4px 4px 0 #999;
}

.neo-brutalist.btn.btn--disabled:hover {
  box-shadow: 4px 4px 0 #999;
  transform: none;
}

@media (max-width: 768px) {
  .message {
    max-width: 90%;
  }
  
  .input-container form {
    flex-direction: column;
  }
  
  .send-button {
    width: 100%;
  }
}
</style>